#!/usr/bin/env python

from __future__ import with_statement

import wx
import model
import threading

class Message(object):
    '''Message class
    
    @author Julot <andy.julot@gmail.com>
    @since Monday, February 27, 2012. 03:05 PM'''
    
    def __init__(self, view, interactor):
        self.view = view
        self.interactor = interactor
    
    def create(self, contactId=None, numbers=[], groups=[]):
        with threading.RLock():
            destinations = []
            message = model.Message()
            if contactId: contact = model.Contact.objects.get(contactId)
            if (not numbers) and (not groups):
                for phone in contact.phones:
                    destinations.append('%s <%s>' % (contact.name, phone))
            elif not groups:
                for number in numbers:
                    destinations.append('%s <%s>' % (contact.name, number))
            else:
                for group in groups:
                    destinations.append(group)
            message.numbers = destinations
            self.view.message.model = message.attributes
    
    def send(self):
        r = self._sendMessage()
        
        if not r:
            s = 'Error. SMS contains illegal value.'
            self.view.messageDialog(s, 'Error', style=wx.OK)
        else:
            self.view.message.destination.Value = ''
        return r
    
    def _sendMessage(self):
        with threading.RLock():
            message = model.Message()
            message.labels = [message.LABEL_OUTBOX]
            message.numbers = self.view.message.destination.Value
            message.message = self.view.message.message.Value
            return message.send()
        